package main

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
	"os"
	"strings"
)

func readDir(files []string, dirPath string) ([]string, error) {
	dirs, err := os.ReadDir(dirPath)
	if err != nil {
		return nil, err
	}
	for _, dir := range dirs {
		if dir.IsDir() {
			files, _ = readDir(files, fmt.Sprintf("%s/%s", dirPath, dir.Name()))
		} else {
			files = append(files, fmt.Sprintf("%s/%s", dirPath, dir.Name()))
		}
	}
	return files, nil
}

func main() {
	ak := os.Getenv("ACCESS_KEY_ID")
	sk := os.Getenv("SECRET_ACCESS_KEY")
	endPoinit := os.Getenv("ENDPOINT")
	bucketName := os.Getenv("BUCKET_NAME")
	target := os.Getenv("TARGET")
	source := os.Getenv("SOURCE")
	obsClient, err := obs.New(ak, sk, endPoinit)
	if err != nil {
		fmt.Println(err.Error(), "obsClient error")
		return
	}
	files := make([]string, 0)
	files, err = readDir(files, source)
	if err != nil {
		fmt.Println(err.Error(), "dir error")
		return
	}
	for _, file := range files {
		input := &obs.UploadFileInput{}
		input.Bucket = bucketName
		input.UploadFile = file
		input.Key = strings.Replace(file, source, target, 1) // localfile为待上传的本地文件路径，需要指定到具体的文件名
		input.EnableCheckpoint = true                        // 开启断点续传模式
		input.PartSize = 10 * 1024 * 1024                    // 指定分段大小为10MB
		input.TaskNum = 5                                    // 指定分段上传时的最大并发数
		_, err := obsClient.UploadFile(input)
		if err != nil {
			fmt.Println(err.Error(), "===obs")
			return
		}
	}
	fmt.Println("upload successful")
	return
}
